import 'package:flutter_bilibili/core/datebase/utils/table_provider.dart';
import 'package:sqflite/sqflite.dart';

import '../model/chat_ message.dart';
import '../utils/table_provider.dart';

///具体的表
class ChatDao extends TableProvider {
  ///表名
  final String name = "ChatMessage";
  final String columnId = "_id";

  @override
  tableName() {
    return name;
  }

  @override
  tableSqlString() {
    return tableBaseString(name, columnId) +
        '''
      id text not null,
      name text)
    ''';
  }

  ///插入数据
  Future<int> insert(ChatMessage message) async {
    Database db = await getDatabase();
    return db.insert(name, message.toJson());
  }

  ///根据ID获取单条数据
  Future<ChatMessage?> getMessageById(String id) async {
    Database db = await getDatabase();
    List<Map<String, dynamic>> maps =
        await db.query(name, where: "id = ?", whereArgs: [id]);
    if (maps.isNotEmpty) {
      ChatMessage message = ChatMessage.fromJson(maps.first);
      return message;
    }
    return null;
  }

  ///获取所有数据
  Future<List<ChatMessage>?> getMessageList() async {
    Database db = await getDatabase();
    List<Map<String, dynamic>> maps = await db.query(name);
    if (maps.isNotEmpty) {
      List<ChatMessage> messages =
          maps.map((e) => ChatMessage.fromJson(e)).toList();
      return messages;
    }
    return null;
  }

  ///删除数据
  Future<int> deleteById(String id) async {
    Database db = await getDatabase();
    return db.delete(name, where: "id = ?", whereArgs: [id]);
  }

  ///更新数据
  Future<int> updateById(String id, String messageName) async {
    Database db = await getDatabase();
    return db.update(name, {"name": messageName},
        where: "id = ?", whereArgs: [id]);
  }
}
